<?php
/**
 * Greendizer PHP Library
 * 
 * @category    Greendizer
 * @package     Greendizer_Collections
 * @subpackage  Greendizer_Collections_Buyers
 * @copyright   Copyright (c) 2009-2010, Greendizer S.A - All rights reserved.
 * @license     Greendizer/Licence.txt
 * @version     1.0
 */

/**
 * @see Greendizer_Collections_ThreadCollectionBase
 */
require_once 'Greendizer/Collections/ThreadCollectionBase.php';

/**
 * @see Greendizer_Resources_Buyers_Thread
 */
require_once 'Greendizer/Resources/Buyers/Thread.php';

/**
 * Represents a collection of buyer threads in Greendizer
 * 
 * @category    Greendizer
 * @package     Greendizer_Collections
 * @subpackage  Greendizer_Collections_Buyers
 * @copyright   Copyright (c) 2009-2010, Greendizer S.A - All rights reserved.
 * @license     Greendizer/License.txt
 */
class Greendizer_Collections_Buyers_ThreadCollection extends Greendizer_Collections_ThreadCollectionBase {

    /**
     * Returns a thread in the collection given its ID
     *
     * @param string $id    Resource ID
     * @return Greendizer_Resources_Buyers_Thread
     * @throws Greendizer_Collections_CollectionException
     */
    public function getResourceById($id) {
        return parent::getResourceById($id);
    }
    
    /**
     * Returns a thread in the collection give its index in the collection
     *
     * @param integer $index    Index of the resource in the collection
     * @return Greendizer_Resources_Vuyers_Thread 
     */
    public function getResourceByIndex($index) {
        return parent::getResourceByIndex($index);
    }
    
    /**
     * Handles responses with code 200 Ok or code 206 Partial Response
     *
     * @param string $method
     * @param Greendizer_Net_Response $response 
     */
    protected function handleOkOrPartialResponse($method, Greendizer_Net_Response $response) {
        parent::handleOkOrPartialResponse($method, $response);

        if ($method == Greendizer_Net_HttpMethods::HEAD)
            return;

        //Parse the json
        $data = json_decode($response->getData());

        //Get the URI of the parent
        $emailUri = new Greendizer_Net_Uri(substr($this->container->getBaseUri()->getAbsoluteUri(), 0, (-1) * strlen('threads/')));

        //Create resource objects from that json and add them to resource dictionary
        $count = 0;
        foreach ($data as $resourceProperties) {
            $resource = new Greendizer_Resources_Buyers_Thread($this->container->getClient(), $emailUri);
            $resource->sync($resourceProperties, Greendizer_Net_Etag::parseEtagString($resourceProperties->etag));
            $this->resources[$resource->getId()] = $resource;
            $this->resourceAsArray[$count] = $resource;
            $count++;
        }
    }

}

?>
